<?php
namespace App\Repository;
use App\Models\Customer\CustomerCoupon;
/**
 * 客户优惠券仓储类
 *
 * @package App\Http\Repository
 * @author WangBin
 * @mail: <849850352@qq.com>
 */
class CustomerCouponRepository extends BaseRepository
{
    /**
     * 检查客户 + 优惠券是否存在
     *
     * @param int $customerId
     * @param int $couponId
     * @return bool
     */
    public function checkExist(int $customerId, int $couponId)
    {
        return CustomerCoupon::query()->where('customer_id', $customerId)->where('coupon_id', $couponId)->exists();
    }

    /**
     * 保存数据
     *
     * @param array $data
     * @param int $entityId
     * @return int|mixed
     */
    public function save(array $data, int $entityId = 0)
    {
        $query = $entityId ? CustomerCoupon::find($entityId) : new CustomerCoupon();
        foreach ($data as $field => $value) {
            $query->{$field} = $value;
        }
        return $query->save() ? $query->entity_id : 0;
    }

    /**
     * 获取客户选择的优惠券
     *
     * @param int $customerId
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     */
    public function getSelected(int $customerId)
    {
        return CustomerCoupon::query()->where('customer_id', $customerId)->where('is_selected', 1)->first();
    }
}
